import 'dart:convert';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:school_assistant/common_client.dart';
import 'package:school_assistant/shop_cart.dart';
import 'package:school_assistant/toast_utils.dart';
import 'package:school_assistant/user_feedback_imgs.dart';
import 'package:sp_util/sp_util.dart';

import 'caipu_page.dart';
import 'common_colors.dart';
import 'data/good_category.dart';
import 'data/goods_entity.dart';
import 'package:collection/collection.dart';

import 'data/goods_moni.dart';
import 'data/order_extra_entity.dart';
import 'package:shake_animation_widget/shake_animation_widget.dart';

class ShopPage extends StatefulWidget {
  const ShopPage({Key? key}) : super(key: key);

  @override
  State<ShopPage> createState() => _ShopPageState();
}

class _ShopPageState extends State<ShopPage> {
  List<GoodCategory> cas = GoodCategory.values;
  Map<int, List<GoodsEntity>> allGoods = {};
  List<GoodsEntity> curGoods = [];
  int cueCate = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff5f5f5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: Text(
          "美味食堂",
          style: TextStyle(
              fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
        ),
        actions: [
          GestureDetector(
            child: Center(
              child: Text(
                "查看菜谱  ",
                style: TextStyle(color: CommonColor.color33),
              ),
            ),
            onTap: () {
              Get.to(CaipuPage());
            },
          )
        ],
      ),
      body: Stack(
        children: [_midContent(), _bottomCart()],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _getGoods();
  }

  _midContent() {
    return Positioned(
        top: 0.5,
        bottom: 64,
        left: 0,
        right: 0,
        child: Flex(
          direction: Axis.horizontal,
          children: [
            Expanded(
                flex: 2,
                child: DecoratedBox(
                  decoration: BoxDecoration(color: CommonColor.colorF5),
                  child: ListView.builder(
                    itemCount: cas.length,
                    itemBuilder: (cxt, index) => _sinCategory(index),
                  ),
                )),
            Expanded(
                flex: 5,
                child: DecoratedBox(
                  decoration: BoxDecoration(color: Colors.white),
                  child: ListView.separated(
                    itemCount: curGoods.length,
                    itemBuilder: (cxt, index) => _sinGoods(index),
                    separatorBuilder: (cxt, index) => Divider(
                      height: 1,
                      color: CommonColor.colorEE,
                    ),
                  ),
                ))
          ],
        ));
  }

  _sinCategory(int index) {
    return GestureDetector(
      child: Container(
        height: 55,
        color: cueCate == cas[index].cid ? Colors.white : CommonColor.colorF5,
        alignment: Alignment.center,
        child: Text(cas[index].name),
      ),
      onTap: () => setState(() {
        cueCate = cas[index].cid;
        curGoods.clear();
        curGoods.addAll(allGoods[cueCate] ?? []);
      }),
    );
  }

  _sinGoods(int index) {
    var good = curGoods[index];
    return Container(
      height: 90,
      alignment: Alignment.center,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 12,
          ),
          CachedNetworkImage(
            height: 65,
            width: 65,
            imageUrl: good.image ?? '',
            imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                  image: imageProvider,
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          SizedBox(
            width: 12,
          ),
          RichText(
              text: TextSpan(children: [
            TextSpan(
                text: good.name ?? "商品名称",
                style: TextStyle(
                    color: CommonColor.color33,
                    fontSize: 15,
                    height: 2,
                    fontWeight: FontWeight.w600)),
            TextSpan(
              text: "\n",
            ),
            TextSpan(
              text: "\n",
            ),
            TextSpan(
                text: '¥ ',
                style: TextStyle(
                    color: CommonColor.colorOri, height: 2, fontSize: 10)),
            TextSpan(
                text: good.price.toString(),
                style: TextStyle(
                    color: CommonColor.colorOri, height: 2, fontSize: 15))
          ])),
          Spacer(),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TextButton(
                style: TextButton.styleFrom(
                    foregroundColor: CommonColor.colorMainGreen,
                    backgroundColor: CommonColor.colorMainGreen,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(3),
                        side: const BorderSide(
                          style: BorderStyle.none,
                        )),
                    minimumSize: const Size(20, 8)),
                onPressed: () {
                  QmToast.toast("添加成功");
                  ShopCart().addGoods(good);
                  setState(() {});
                },
                child: Text(
                  "添加",
                  style: TextStyle(color: CommonColor.color33, fontSize: 10),
                ),
              ),
              SizedBox(
                height: 2,
              )
            ],
          ),
          SizedBox(
            width: 10,
          )
        ],
      ),
    );
  }

  _sinGoods2(int index) {
    var good = ShopCart().shopGoods[index];
    return Container(
      height: 90,
      alignment: Alignment.center,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 12,
          ),
          CachedNetworkImage(
            height: 65,
            width: 65,
            imageUrl: good.image ?? '',
            imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                  image: imageProvider,
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          SizedBox(
            width: 12,
          ),
          RichText(
              text: TextSpan(children: [
            TextSpan(
                text: good.name ?? "商品名称",
                style: TextStyle(
                    color: CommonColor.color33,
                    fontSize: 15,
                    height: 2,
                    fontWeight: FontWeight.w600)),
            TextSpan(
              text: "\n",
            ),
            TextSpan(
              text: "\n",
            ),
            TextSpan(
                text: '¥ ',
                style: TextStyle(
                    color: CommonColor.colorOri, height: 2, fontSize: 10)),
            TextSpan(
                text: good.price.toString(),
                style: TextStyle(
                    color: CommonColor.colorOri, height: 2, fontSize: 15))
          ])),
          Spacer(),
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TextButton(
                style: TextButton.styleFrom(
                    foregroundColor: CommonColor.colorMainGreen,
                    backgroundColor: CommonColor.colorMainGreen,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(3),
                        side: const BorderSide(
                          style: BorderStyle.none,
                        )),
                    minimumSize: const Size(20, 8)),
                onPressed: () {
                  QmToast.toast("取消成功");
                  ShopCart().delGoods(good);
                  numberNotifier.value = ShopCart().shopGoods.length;
                  setState(() {});
                },
                child: Text(
                  "取消",
                  style: TextStyle(color: CommonColor.color33, fontSize: 10),
                ),
              ),
              SizedBox(
                height: 2,
              )
            ],
          ),
          SizedBox(
            width: 10,
          )
        ],
      ),
    );
  }

  _bottomCart() {
    return Positioned(
        bottom: 0,
        left: 0,
        right: 0,
        child: GestureDetector(
          child: Container(
            height: 64,
            decoration: const BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                    color: Colors.black12,
                    offset: Offset(0.0, 6.0),
                    blurRadius: 8,
                    spreadRadius: 4)
              ],
            ),
            child: Row(
              children: [
                const SizedBox(
                  width: 18,
                ),
                Image.asset(
                  UserFeedBackImgs.shop_cart,
                  width: 35,
                ),
                const SizedBox(
                  width: 15,
                ),
                RichText(
                    text: TextSpan(children: [
                  TextSpan(
                      text: "合计\n",
                      style: TextStyle(color: Color(0xff333333), fontSize: 14)),
                  TextSpan(
                      text: "¥ ",
                      style: TextStyle(color: Color(0xffFF8000), fontSize: 10)),
                  TextSpan(
                      text: ShopCart().getGoodsPrice().toString(),
                      style: TextStyle(color: Color(0xffFF8000), fontSize: 18))
                ])),
                const Spacer(),
                TextButton(
                  style: TextButton.styleFrom(
                      foregroundColor: CommonColor.colorMainGreen,
                      backgroundColor: CommonColor.colorMainGreen,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3),
                          side: const BorderSide(
                            style: BorderStyle.none,
                          )),
                      minimumSize: const Size(80, 30)),
                  onPressed: () {
                    setState(() {
                      ShopCart().clear();
                    });
                  },
                  child: Text(
                    "重新选",
                    style: TextStyle(color: CommonColor.color33, fontSize: 14),
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                TextButton(
                  style: TextButton.styleFrom(
                      foregroundColor: CommonColor.colorMainGreen,
                      backgroundColor: CommonColor.colorMainGreen,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3),
                          side: const BorderSide(
                            style: BorderStyle.none,
                          )),
                      minimumSize: const Size(80, 30)),
                  onPressed: () {
                    showBottomSheet();
                    //_addGood();
                    // if (ShopCart().shopGoods.isEmpty) {
                    //   QmToast.toast("请至少选选一个商品");
                    //   return;
                    // }
                    // _createOrder();
                  },
                  child: Text(
                    "选好了",
                    style: TextStyle(color: CommonColor.color33, fontSize: 14),
                  ),
                ),
                const SizedBox(
                  width: 18,
                )
              ],
            ),
          ),
          onTap: () => showBottomSheet(),
        ));
  }

  _addGood() async {
    try {
      List goodsall = [
        Moni().goods1,
        Moni().goods2,
        Moni().goods3,
        Moni().goods4,
        Moni().goods5,
        Moni().goods6,
        Moni().goods7,
        Moni().goods8,
        Moni().goods9,
        Moni().goods10,
      ];
      goodsall.forEach((element11) {
        element11.forEach((element) async {
          var res = await CommonClient()
              .addGood(element[0], element[1], element[2], element[3]);
          print(res);
        });
      });
    } catch (e) {
      print(e);
    }
  }

  void showBottomSheet() {
    showModalBottomSheet(
      builder: (BuildContext context) {
        //构建弹框中的内容
        return AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets, // 我们可以根据这个获取需要的padding
          duration: const Duration(milliseconds: 100),
          child: Container(
            height: 300,
            padding: EdgeInsets.all(12),
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      "合计:  ",
                      style: TextStyle(
                          color: CommonColor.color33,
                          fontSize: 20,
                          fontWeight: FontWeight.w600),
                    ),
                    Text(
                      "¥",
                      style: TextStyle(
                          color: CommonColor.colorOri,
                          fontSize: 16,
                          fontWeight: FontWeight.w600),
                    ),
                    ValueListenableBuilder(
                      valueListenable: numberNotifier,
                      builder:
                          (BuildContext context, int value, Widget? child) {
                        return Text(
                          ShopCart().getGoodsPrice().toString(),
                          style: TextStyle(
                              color: CommonColor.colorOri,
                              fontSize: 20,
                              fontWeight: FontWeight.w600),
                        );
                      },
                    ),
                    Spacer(),
                    GestureDetector(
                      child: Container(
                        padding:
                            EdgeInsets.symmetric(vertical: 6, horizontal: 16),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: CommonColor.colorMainGreen,
                            borderRadius: BorderRadius.circular(4)),
                        child: Text(
                          "确认",
                          style: TextStyle(
                              color: CommonColor.color33, fontSize: 14),
                        ),
                      ),
                      onTap: () {
                        _createOrder();
                        Get.back();
                      },
                    ),
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                Expanded(
                  child: ShopCart().shopGoods.length == 0
                      ? Container(
                          child: Center(
                            child: Text("暂无商品"),
                          ),
                        )
                      : ValueListenableBuilder(
                          valueListenable: numberNotifier,
                          builder:
                              (BuildContext context, int value, Widget? child) {
                            return ListView.builder(
                              itemBuilder: (cxt, index) => _sinGoods2(index),
                              itemCount: ShopCart().shopGoods.length,
                            );
                          },
                        ),
                ),
              ],
            ),
          ),
        );
      },
      context: context,
    );
  }

  ValueNotifier<int> numberNotifier = new ValueNotifier(0);

  _createOrder() async {
    try {
      var code = Random().nextInt(1000000).toString();
      var extra = OrderExtraEntity();
      extra.time = DateTime.now().toLocal().toString().substring(0, 19);
      extra.price = ShopCart().getGoodsPrice().toString();
      extra.code = code;
      var res = await CommonClient().createOrder(
          SpUtil.getString("uid") ?? '', jsonEncode(ShopCart().shopGoods),
          extra: jsonEncode(extra));
      setState(() {
        _shocode(code);
        ShopCart().clear();
      });
      // Get.back();
    } catch (e) {
      print(e);
    }
  }

  _shocode(String code) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("下单成功"),
          content: Text("您的取单号为:  " + code),
          actions: [
            TextButton(
              onPressed: () {
                Get.back();
              },
              child: const Text('确认'),
            ),
          ],
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        );
      },
    );
  }

  _getGoods() async {
    try {
      EasyLoading.show(status: 'loading...');
      allGoods.clear();
      var res = await CommonClient().getGoods(1, 100);
      List<dynamic> data = jsonDecode(res.data ?? "");
      List<GoodsEntity> gs = [];
      if (data != null) {
        data.forEach((element) {
          gs.add(GoodsEntity.fromJson(element));
        });
        allGoods = groupBy(gs, (p0) => p0.category ?? 0);
      }
      setState(() {
        curGoods.clear();
        curGoods.addAll(allGoods[cueCate] ?? []);
      });
      print(res);
    } catch (e) {
      print(e);
    } finally {
      EasyLoading.dismiss();
    }
  }
}
